require(['./config'], function() {
    require(['jquery', 'template', 'loadHAF'], function($, template) {
        class Detail {
            constructor() {
                this.cart = JSON.parse(localStorage.getItem("cart")) || []
                this.init()
                this.addListener()
            }
            init() {
                const _id = window.location.search.slice(4)
                const url = `http://www.xiongmaoyouxuan.com/api/detail?id=${_id}` /* 魅族手机*/
                $.getJSON(url, resp => {
                    const _prod = resp.data.detail
                    const data = { prod: _prod }
                    const html = template("dtailList", data)
                    $(".hBox").prepend(html)
                })
            }
            addListener() {
                $(".hBox").on("submit", ".get-to-cart", this.addToCart.bind(this))
            }
            addToCart(e) {
                e.preventDefault()
                const parents = $(e.target).parents(".detail_hBox")
                const currProd = {
                    id: parents.data("id"),
                    title: parents.find(".prod-title").text(),
                    img: parents.find(".prod-img").attr("src"),
                    price: parents.find(".prod-price").text(),
                    amount: 1
                }
                this.cart = JSON.parse(localStorage.getItem("cart")) || []

                const has = this.cart.some(prod => prod.id == currProd.id)
                if (has) {
                    this.cart = this.cart.map(prod => {
                        if (prod.id == currProd.id)
                            prod.amount += 1
                        return prod
                    })
                } else {
                    this.cart.push(currProd)
                }
                localStorage.setItem("cart", JSON.stringify(this.cart))
            }
        }
        new Detail()
    })
})